package com.soft.bams.dao;

import com.soft.bams.entity.Account;

/**
 * @author yzh
 * @desc TODO
 * @date 2025/4/17
 */
public class ArrayDao implements IDao<Account , Account[]>{
    private Account[] account;
    private int index;

    public ArrayDao() {
        account = new Account[10];
        index = 0;
    }

    private Long id = 100000000000000000L;

    @Override
    public Long getId() {
        return this.id;
    }

    @Override
    public void setId(Long id) {
        this.id = id;
    }

    // 插入账户
    public boolean insert(Account acc) {
        if (index >= account.length) {
            // 扩容
            Account[] newAccount = new Account[account.length * 3 / 2 + 1];
            System.arraycopy(account, 0, newAccount, 0, account.length);
            account = newAccount;
        }
        account[index++] = acc;
        return true;
    }

    // 根据id和密码查询账户
    public Account selectOne(Long id, String pwd) {
        for (int i = 0; i < index; i++) {
            Account acc = account[i];
            if (acc != null && acc.getId().equals(id) && acc.getPassword().equals(pwd)) {
                return acc;
            }
        }
        return null;
    }

    // 根据id查询账户
    public Account selectOne(Long id) {
        for (int i = 0; i < index; i++) {
            Account acc = account[i];
            if (acc != null && acc.getId().equals(id)) {
                return acc;
            }
        }
        return null;
    }

    // 查询所有账户
    public Account[] selectAll() {
        return account;
    }

    // 删除账户
    /*public boolean delete(Long id) {
        for (int i = 0; i < index; i++) {
            if (account[i].getId().equals(id)) {
                // 将最后一个元素移到当前位置
                account[i] = account[index - 1];
                account[index - 1] = null;
                index--;
                return true;
            }
        }
        return false;
    }*/

    public boolean update(Account acc) {
        for (int i = 0; i < index; i++) {
            if (account[i] != null && account[i].getId().equals(acc.getId())) {
                account[i] = acc;
                return true;
            }
        }
        return false;
    }

    public int getIndex() {
        return index;
    }
}
